'use strict';
const express = require('express')
const bodyParser = require('body-parser');
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
//策略
passport.use(new LocalStrategy({
    usernameField: 'name',
    passwordField: 'psd'
}, function(username, password, done) {
    if (username === 'gay' && password === '123') {
        done(null, true);
    } else {
        done(null, false, {
            message: '用户名或密码不对'
        })
    }
}));
app.use(passport.initialize());
//路由
// app.post('/v1/login', passport.authenticate('local'));
//====================================================================
function authMiddle() {
    return function(req, res, next) {
        passport.authenticate('local', function(err, user, info) {
            if (err) return next(err);
            if (!user) return res.status(401).end('Unauthorized:' + info.message);
            next();
        })(req, res, next);
    }
}
app.post('/v2/login', authMiddle(), function(req, res) {
    res.end('very nice !');
})
app.listen(3000, function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('server start at 3000');
    }
})